#include "../Server.hpp"

class EchoServer
{
private:
    TCPServer _server;

    void OnMessage(const PtrConnection &conn, Buffer *buf)
    {
        std::cout << "message thread id: " << std::this_thread::get_id() << std::endl;
        conn->Send(buf->ReadBegin(), buf->ReadAbleSize());
        buf->ConfirmReadSize(buf->ReadAbleSize());
        // conn->Shutdown();
    }

    void OnConnected(const PtrConnection &conn)
    {
        std::cout << "New Connection: " << conn.get() << std::endl;
    }

    void OnClosed(const PtrConnection &conn)
    {
        std::cout << "Closed Connection: " << conn.get() << std::endl;
    }

public:
    EchoServer(int port) : _server(port)
    {
        _server.SetThreadCount(2);
        _server.EnableInactiveRelease(10);
        _server.SetClosedCallback(std::bind(&EchoServer::OnClosed, this, std::placeholders::_1));
        _server.SetConnectedCallback(std::bind(&EchoServer::OnConnected, this, std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&EchoServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
    }
    ~EchoServer() {}
    void Start() { _server.Start(); }
};

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << " local-port" << std::endl;
        exit(0);
    }
    uint16_t port = std::stoi(argv[1]);
    EchoServer server(port);
    server.Start();
    return 0;
}
